/**
 * Copyright (c) 2012 Ben Murphy (Smurph)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.smurph.expandablelist.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

import com.smurph.expandablelist.R;
import com.smurph.expandablelist.database.DBHelper;
import com.smurph.expandablelist.provider.TblABC.ABCs;
import com.smurph.expandablelist.provider.TblName.Names;

public class MyContentProvider extends ContentProvider {

	private static String TAG;
	public static final String AUTHORITY = "com.smurph.androidexpandlist.provider";
	
	private static final int mTblNames_ID = 100;
	private static final int mTblAbc_ID = 101;
	private static final int mNames_Abc_ID = 102;
	
	private static final UriMatcher sUriMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);
	static {
		sUriMatcher.addURI(AUTHORITY, Names.TBL_NAMES, mTblNames_ID);
		sUriMatcher.addURI(AUTHORITY, ABCs.TBL_ABC, mTblAbc_ID);
		sUriMatcher.addURI(AUTHORITY, Names.TBL_NAMES + "/#", mNames_Abc_ID);
	}

    private Context mContext;
    private DBHelper mDbHelper = null;
    private SQLiteDatabase mDB = null;
    
	@Override
	public boolean onCreate() {
		mContext = getContext();
		mDbHelper = new DBHelper(mContext);
		TAG = mContext.getString(R.string.log_tag);
		return (mDbHelper == null) ? false : true;
	}

	public boolean isDBOpen() {
		if (mDB == null)
			this.mDB = mDbHelper.getWritableDatabase();
		return (mDB == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		if (!isDBOpen()) return null;
		
		SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
        String[] defaultProjection = null;
        String groupBy = null;
		
		int uriMatch = sUriMatcher.match(uri);
		switch (uriMatch) {
		case mTblNames_ID:
			break;
		case mTblAbc_ID:
			qBuilder.setTables(ABCs.TBL_ABC);
            defaultProjection = ABCs.DEFAULT_PROJECTION;
			break;
		case mNames_Abc_ID:
			qBuilder.setTables(Names.NAMES_ABC_JOIN);
			defaultProjection = new String[] { Names.TBL_NAMES + "." + Names._ID, Names.TBL_NAMES + "." + Names.NAME };
			qBuilder.appendWhere( ABCs.TBL_ABC + "." + ABCs._ID + "=" + uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
		
		// TODO: Check columns in incoming projection to make sure they're valid
        projection = (projection == null) ? defaultProjection : projection;
        Cursor c = null;
        try {
			c = qBuilder.query(mDB, projection, selection, selectionArgs,
					groupBy, null, sortOrder);
        } catch (SQLiteException e) {
            Log.e(TAG, "Query failed, returning null cursor.", e);
        }
        c.setNotificationUri(mContext.getContentResolver(), uri);
        return c;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}
}
